﻿using ClosedXML.Excel;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace D.Medicalcare.Write.API.Controllers
{
    /// <summary>
    /// 门诊消费记录控制器-写
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DoorSpendController : ControllerBase
    {
        private readonly IBaseRepository<DoorSpend> baseRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository"></param>
        public DoorSpendController(IBaseRepository<DoorSpend> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();

            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    try
                    {
                        await file.CopyToAsync(stream);
                        stream.Position = 0; // 重置流的位置
                    }
                    catch (Exception ex)
                    {
                        result.Code = APIEnum.Failed;
                        result.Msg = "文件读取失败：" + ex.Message;
                        return StatusCode(500, result);
                    }

                    try
                    {
                        using (var workbook = new XLWorkbook(stream))
                        {
                            var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                            var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                            List<DoorSpend> inventoriesList = new List<DoorSpend>();

                            foreach (var row in rows)
                            {
                                var inventory = new DoorSpend();

                                // 尝试解析日期
                                string dateStr = row.Cell(1).GetValue<string>();
                                if (DateTime.TryParse(dateStr, out DateTime opTime))
                                {
                                    inventory.OPTime = opTime;
                                }
                                else
                                {
                                    result.Code = APIEnum.Failed;
                                    result.Msg = $"导入失败，第 {row.RowNumber()} 行的日期格式错误：{dateStr}";
                                    return StatusCode(500, result);
                                }

                                inventory.OrderId = row.Cell(2).GetValue<string>();
                                inventory.Name = row.Cell(3).GetValue<string>();
                                inventory.PatientNo = row.Cell(4).GetValue<string>();
                                inventory.BusinessType = row.Cell(5).GetValue<string>();
                                inventory.MoneyType = row.Cell(6).GetValue<string>();
                                inventory.PayType = row.Cell(7).GetValue<string>();
                                inventory.Money = row.Cell(8).GetValue<decimal>();
                                inventory.PaymentStatus = row.Cell(9).GetValue<string>();

                                // 添加到要插入的列表中
                                inventoriesList.Add(inventory);
                            }

                            // 将数据批量插入数据库
                            await baseRepository.AddRangeAsync(inventoriesList);

                            result.Code = APIEnum.Success;
                            result.Msg = "导入成功";
                            result.Data = inventoriesList.Count;
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Code = APIEnum.Failed;
                        result.Msg = "Excel 文件解析失败：" + ex.Message;
                        return StatusCode(500, result);
                    }
                }
            }
            catch (FormatException ex)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "导入失败，Excel 文件中数据格式错误：" + ex.Message;
                return StatusCode(500, result);
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "导入失败，发生未知错误：" + ex.Message;
                return StatusCode(500, result);
            }

            return Ok(result);
        }


    }
}
